<template>
  <!-- 折线轨迹图 -->
  <div id="container" style="width: 100vw; height: 90vh" />
</template>

<script setup>

import { lazyAMapApiLoaderInstance } from '~/services/injected-amap-api-instance'
let map = shallowRef(null)
let marker = shallowRef(null)

//绘制线路需要的坐标
let lineArr = ref([
  [116.478935, 39.997761],
  [116.478939, 39.997825],
  [116.478912, 39.998549],
  [116.478912, 39.998549],
  [116.478998, 39.998555],
  [116.478998, 39.998555],
  [116.479282, 39.99856],
  [116.479658, 39.998528],
  [116.480151, 39.998453],
  [116.480784, 39.998302],
  [116.480784, 39.998302],
  [116.481149, 39.998184],
  [116.481573, 39.997997],
  [116.481863, 39.997846],
  [116.482072, 39.997718],
  [116.482362, 39.997718],
  [116.483633, 39.998935],
  [116.48367, 39.998968],
  [108.983569, 34.285675],
  [106.205794, 38.458831],
  [111.761777, 40.875595],
  [103.85094, 35.987496],
])
let firstArr = ref([116.478935, 39.997761]) //中心点/初始坐标

lazyAMapApiLoaderInstance.then(() => {
  initMap()
})

function initMap() {
  map.value = new AMap.Map('container', {
    resizeEnable: true, // 窗口大小调整
    center: firstArr.value, // 中心 firstArr: [116.478935, 39.997761],
    zoom: 5,
    viewMode: '3D', // 地图模式
    terrain: true, // 开启地形图
  })
  // 添加工具栏
  map.value.plugin(['AMap.ToolBar', 'AMap.Scale'], () => {
    // 工具条
    const toolbar = new AMap.ToolBar()
    // 比例尺
    const scale = new AMap.Scale()
    map.value.addControl(toolbar)
    map.value.addControl(scale)
  })
  // 添加maker
  marker.value = new AMap.Marker({
    map: map.value,
    position: firstArr.value,
    icon: 'https://webapi.amap.com/images/car.png',
    offset: new AMap.Pixel(-26, -13), // 调整图片偏移
    autoRotation: true, // 自动旋转
    angle: -90, // 图片旋转角度
  })
  // maker点击事件
  marker.value.on('click', function (e) {
    console.log(`我被点击啦---`, e)
    initroad() //点击maker绘制轨迹
  })
}
function initroad() {
  AMap.plugin('AMap.MoveAnimation', function () {
    // 绘制还未经过的路线
    let polyline = new AMap.Polyline({
      map: map.value,
      path: lineArr.value,
      showDir: true,
      strokeColor: '#000', // 线颜色--蓝色
      // strokeOpacity: 1,     //线透明度
      strokeWeight: 6, // 线宽
      // strokeStyle: "solid"  //线样式
      lineJoin: 'round', // 折线拐点的绘制样式
    })
    // 绘制路过了的轨迹
    var passedPolyline = new AMap.Polyline({
      map: map.value,
      strokeColor: '#AF5', // 线颜色-绿色
      // path: lineArr.reverse(),
      // strokeOpacity: 1,     //线透明度
      strokeWeight: 6, // 线宽
      // strokeStyle: "solid"  //线样式
    })
    marker.value.on('moving', e => {
      passedPolyline.setPath(e.passedPath)
      polyline.setPath(e.passedPath)
      // map.value.setCenter(e.target.getPosition(), true)
    })
  })
  map.value.setFitView()
}
</script>
